package com.project.base.baseproject.HttpService;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;

import com.google.gson.Gson;
import com.project.base.baseproject.AppCustoms.Tool.StringUtil;
import com.project.base.baseproject.HttpService.InterfaceConfig;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.CipherSuite;
import com.squareup.okhttp.ConnectionSpec;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.TlsVersion;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import static java.lang.String.valueOf;

/**
 * Created by mac on 2016/11/28.
 */
//基础网络请求封装  回传string数据 外面自己处理
public class HttpService {
    //请求方式
    public static int E_HTTP_REQUEST_METHOD_GET = 0;
    public static int E_HTTP_REQUEST_METHOD_POST = 1;
    static Gson gson = new Gson();
    //下载文件 网络路径 本地路径 回调
    public static void downloadFile(String urlPath,String localFileUrl,final Handler handler) {
        final OkHttpClient mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(60, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
        final File resultFile = new File(localFileUrl);
        final Request request = new Request.Builder().url(urlPath).build();
        final Call call = mOkHttpClient.newCall(request);
        final Message message = new Message();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                message.what = 1;
                message.obj = e.toString();
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                long total = response.body().contentLength();
                long current = 0;
                is = response.body().byteStream();
                fos = new FileOutputStream(resultFile);
                while ((len = is.read(buf)) != -1) {
                    current += len;
                    fos.write(buf, 0, len);
                }
                fos.flush();
                is.close();
                fos.close();
                message.what = 0;
                message.obj = "下载成功";
                //主线程回传消息 handleMessage()方法重的代码就是在主线程中运行的
                handler.sendMessage(message);
            }
        });
    }
    //上传文件类型的请求 都是post方法
    public static void uploadFile(String urlPath, Map<String,String> parameters, Bitmap bitmap, String name,final Handler handler) {
        final OkHttpClient client = new OkHttpClient();
        //bitmap 转换成 byte
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //0-100之间 不能取0 100
        bitmap.compress(Bitmap.CompressFormat.PNG, 99, baos);
        //压缩一下
        byte[] byteArray = baos.toByteArray();
        // form 表单形式上传
        MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
        // MediaType.parse() 里面是上传的文件类型。
        RequestBody body = RequestBody.create(MediaType.parse("image/png"), byteArray);
        //当前时间作为文件名
        String filename = System.currentTimeMillis() + ".png";
        // 参数分别为， 请求key ，文件名称 ， RequestBody
        builder.addFormDataPart(name, filename, body);
        if (parameters != null) {
            // map 里面是请求中所需要的 key 和 value
            for (Map.Entry entry : parameters.entrySet()) {
                builder.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
            }
        }
        Request request = new Request.Builder().url(InterfaceConfig.KB_API_DOMAIN + urlPath).post(builder.build()).build();
        final Message message = new Message();
        client.setConnectTimeout(60, TimeUnit.SECONDS);
        client.setWriteTimeout(60, TimeUnit.SECONDS);
        client.setReadTimeout(60, TimeUnit.SECONDS);
        //发送异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                message.what = 1;
                message.obj = e.toString();
                //主线程回传消息
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(Response response) throws IOException {
                message.what = 0;
                message.obj = "请求失败";
                //把返回的数据转成字典
                Map map = gson.fromJson(response.body().string(),Map.class);
                //如果返回代码为0，表示成功
                if(map.containsKey("code") &&
                        map.get("code").toString().equals("0.0")) {
                    message.what = 0;
                    message.obj = map.get("data");
                } else {
                    message.what = 1;
                    if(map.containsKey("message"))
                        message.obj = map.get("message");
                }
                //主线程回传消息
                handler.sendMessage(message);
            }
        });
    }
    //发送普通请求
    public static void sendRequest(int requestMethod, String urlPath, Map<String,String> parameters, final Handler handler) {
//        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
//                .tlsVersions(TlsVersion.TLS_1_2)
//                .cipherSuites(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
//                .build();
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(60,TimeUnit.SECONDS);
        client.setWriteTimeout(60, TimeUnit.SECONDS);
        client.setReadTimeout(60, TimeUnit.SECONDS);
//        client.setConnectionSpecs(Collections.singletonList(spec));
        Request request = null;
        //get方式
        if (requestMethod == HttpService.E_HTTP_REQUEST_METHOD_GET) {
            urlPath = urlPath + "?";
            for (Map.Entry<String ,String> entry : parameters.entrySet()) {
                if(StringUtil.isBlank(entry.getValue()))
                    continue;
                urlPath = urlPath + entry.getKey() + "=" + entry.getValue() + "&";
            }
            //去掉最后的&符号，不然会报错Object reference not set to an instance of an object
            if(urlPath.length() > 0)
                urlPath = urlPath.substring(0,urlPath.length() - 1);
            request = new Request.Builder().url(InterfaceConfig.KB_API_DOMAIN + urlPath).build();
        }
        //post方式
        if (requestMethod == HttpService.E_HTTP_REQUEST_METHOD_POST) {
            FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
            for (Map.Entry<String ,String> entry : parameters.entrySet()) {
                if(StringUtil.isBlank(entry.getValue()))
                    continue;
                formEncodingBuilder.add(entry.getKey(), entry.getValue());
            }
            RequestBody formBody = formEncodingBuilder.build();
            request = new Request.Builder().url(InterfaceConfig.KB_API_DOMAIN + urlPath).post(formBody).build();
        }
        final Message message = new Message();
        //发送异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                message.what = 1;
                message.obj = e.toString();
                //主线程回传消息
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(Response response) throws IOException {
                //是不是一个json字符串
                String resultString = response.body().string();
                if(StringUtil.isJson(resultString)) {
                    //如果第一个字符是{就是字典
                    if(resultString.substring(0,1).equals("{")) {
                        Map resultMap = gson.fromJson(resultString,Map.class);
                        //返回如果有code 表示具有 code data message结构
                        if (resultMap.containsKey("code")) {
                            if (resultMap.get("code").toString().equals("0.0")) {
                                message.obj = resultMap.get("data");
                            } else {
                                message.what = 1;
                                if (resultMap.containsKey("message"))
                                    message.obj = resultMap.get("message");
                                else
                                    message.obj = "请求失败";
                            }
                            //出错了 不包含code 但是包含Message
                        } else if(resultMap.containsKey("Message")){
                            message.what = 1;
                            message.obj = resultMap.get("Message");
                        } else {
                            message.obj = resultMap;
                        }
                    }
                    //如果第一个字符是[就是字典
                    else if(resultString.substring(0,1).equals("[")) {
                        message.obj = gson.fromJson(resultString,Array.class);
                    }
                    //如果都不是，说明又出现了错误
                    else {
                        message.what = 1;
                        message.obj = resultString;
                    }
                } else {
                    message.obj = resultString;
                }
                //主线程回传消息
                handler.sendMessage(message);
            }
        });
    }
}
